<template>
  <div class="image-component">
    <img 
      v-if="imageUrl" 
      :src="imageUrl" 
      :alt="altText"
      :style="imageStyle"
      @error="handleImageError"
      @load="handleImageLoad"
    />
    <div 
      v-else 
      class="image-placeholder"
      @click="selectImage"
      :style="placeholderStyle"
    >
      <i class="el-icon-picture placeholder-icon"></i>
      <p class="placeholder-text">{{ previewMode ? '图片加载失败' : '点击选择图片' }}</p>
    </div>
    
    <!-- 图片上传对话框 -->
    <el-dialog
      title="选择图片"
      v-model="uploadDialogVisible"
      width="500px"
      v-if="!previewMode"
    >
      <el-upload
        class="image-uploader"
        :action="uploadAction"
        :show-file-list="false"
        :on-success="handleUploadSuccess"
        :on-error="handleUploadError"
        :before-upload="beforeUpload"
        accept="image/*"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip">
            只能上传jpg/png文件，且不超过2MB
          </div>
        </template>
      </el-upload>
      
      <div class="url-input-section">
        <el-divider>或直接输入图片URL</el-divider>
        <el-input
          v-model="imageUrlInput"
          placeholder="请输入图片URL"
          @keydown.enter="handleUrlConfirm"
        >
          <template #append>
            <el-button @click="handleUrlConfirm">确定</el-button>
          </template>
        </el-input>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="uploadDialogVisible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { Message } from 'element-ui'
import type { ComponentConfig } from '../../interface'

// Props
interface Props {
  componentData: ComponentConfig
  previewMode?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  previewMode: false
})

// Emits
const emit = defineEmits<{
  update: [property: string, value: any]
}>()

// 响应式数据
const uploadDialogVisible = ref(false)
const imageUrlInput = ref('')
const uploadAction = ref('/api/upload/image') // 配置上传接口

// 计算属性
const imageUrl = computed(() => {
  return props.componentData.props?.src || ''
})

const altText = computed(() => {
  return props.componentData.props?.alt || '图片'
})

const imageStyle = computed(() => {
  const style = props.componentData.style || {}
  return {
    width: '100%',
    height: '100%',
    objectFit: style.objectFit || 'contain',
    borderRadius: style.borderRadius || '0',
    ...style
  }
})

const placeholderStyle = computed(() => {
  const style = props.componentData.style || {}
  return {
    backgroundColor: style.backgroundColor || '#f5f5f5',
    borderRadius: style.borderRadius || '0',
    border: style.border || '1px dashed #ddd',
  }
})

// 选择图片
const selectImage = () => {
  if (props.previewMode) return
  uploadDialogVisible.value = true
  imageUrlInput.value = imageUrl.value
}

// 处理URL确认
const handleUrlConfirm = () => {
  if (imageUrlInput.value.trim()) {
    emit('update', 'props.src', imageUrlInput.value.trim())
    uploadDialogVisible.value = false
  } else {
    Message.warning('请输入有效的图片URL')
  }
}

// 上传前检查
const beforeUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    Message.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    Message.error('上传文件大小不能超过 2MB!')
    return false
  }
  return true
}

// 上传成功
const handleUploadSuccess = (response: any) => {
  if (response.success && response.data?.url) {
    emit('update', 'props.src', response.data.url)
    uploadDialogVisible.value = false
    Message.success('图片上传成功')
  } else {
    Message.error('图片上传失败')
  }
}

// 上传失败
const handleUploadError = () => {
  Message.error('图片上传失败')
}

// 图片加载失败
const handleImageError = () => {
  console.warn('图片加载失败:', imageUrl.value)
}

// 图片加载成功
const handleImageLoad = () => {
  console.log('图片加载成功:', imageUrl.value)
}
</script>

<style lang="scss" scoped>
.image-component {
  width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden;
}

.image-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;

  &:hover {
    background-color: #f0f0f0 !important;
  }

  .placeholder-icon {
    font-size: 48px;
    color: #ccc;
    margin-bottom: 8px;
  }

  .placeholder-text {
    margin: 0;
    font-size: 14px;
    color: #999;
  }
}

.image-uploader {
  :deep(.el-upload) {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: 0.2s;

    &:hover {
      border-color: #409eff;
    }
  }

  :deep(.el-icon--upload) {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
  }
}

.url-input-section {
  margin-top: 20px;
}

.dialog-footer {
  text-align: right;
}
</style>
